package com.xing.game.netty.server;

import com.xing.game.netty.WorkerFactory;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;


public class NetServer {
	private ChannelGroup group = new DefaultChannelGroup();
	private WorkerFactory factory;
	private ServerBootstrap bootstrap;
	private int port;

	public NetServer(WorkerFactory factory, int port) {
		this.factory = factory;
		this.port = port;
	}

	public NetServer start() {
		bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		bootstrap.setPipelineFactory(new NetServerPiplineFactory(group, factory));
		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);
		bootstrap.setOption("child.sendBufferSize", 8192 << 2);
		bootstrap.setOption("child.receiveBufferSize", 4096);
		group.add(bootstrap.bind(new InetSocketAddress(port)));
		return this;
	}

	public void stop() {
		if (group != null) {
			group.close().awaitUninterruptibly();
		}
		if (bootstrap != null) {
			bootstrap.releaseExternalResources();
		}
	}
}
